package DML;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import util.Methods;
import DuiXiang.TableModel;

public class UpdateTable {

	@SuppressWarnings("finally")
	public static int updateTable(String dataBaseName, String tableName, List<String> setName, List<String> setValues, List<String> name, List<String> values) {
		int i,j,number1,number2;
		int[] temp = new int[20];
		int[] tem = new int[20];
		String dbfpath = "D:\\database\\" + dataBaseName + "\\"+ tableName + ".dbf";
		String datpath = "D:\\database\\" + dataBaseName + "\\"+ tableName + ".dat";
		List<List<String>> tableContent = util.readTable(datpath);
		List<TableModel> tableModelList = util.ReadTableModelList(dbfpath);//获取表的字段信息
		if(tableContent==null)
			return -1;										//无此表或数据库
		number1=0;
		for(String nn:name){
			i=0;
			for(TableModel aa:tableModelList){
				if(aa.getsFieldName().equals(nn))
					break;
				i++;
			}
			temp[number1++]=i;
		}
		number2=0;
		for(String nn:setName){
			i=0;
			for(TableModel aa:tableModelList){
				if(aa.getsFieldName().equals(nn)&&aa.getbKey()=='y'){
					return -5;			//主键不能修改
				}
				if(aa.getsFieldName().equals(nn))
					break;
				i++;
			}
			tem[number2++]=i;
		}
		j=0;
		for(int k=0;k<tableContent.size();k++){
			List<String> aline = tableContent.get(k); 
			for(i=0;i<number1;i++){
				String a=aline.get(temp[i]);
				String b=values.get(i);
				if(!a.equals(b))
					break;
			}
			if(i==number1){
				for(i=0;i<number2;i++)
					aline.set(tem[i], setValues.get(i));
			}
			tableContent.set(j, aline);
			j++;
		}
		File file = new File(datpath);
		if(file.delete())
			System.out.println("修改成功");
		else{
			System.out.println("修改失败");
			return 0;								//删除失败,暂定0
		}
		
		
		FileWriter fileWriter = null;
		BufferedWriter bufferWriter = null;
		try {
			fileWriter = new FileWriter(datpath);
			bufferWriter = new BufferedWriter(fileWriter);
			for (List<String> aline1 : tableContent) {
				for (int k=0;k<aline1.size();k++) {
					bufferWriter.write(aline1.get(k));
					if(k<aline1.size()-1)
						bufferWriter.write(",");
					else
						bufferWriter.newLine();
					bufferWriter.flush();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		} finally {
			try {
				bufferWriter.close();
				fileWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return 1;
		}
	}

}
